<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2019/3/10
 * Time: 22:59
 */

namespace app\index\controller;

use app\common\controller\Jwt;
use think\Controller;
use think\App;
use think\facade\Config;
use think\facade\Log;

class Base extends Controller{
    protected static $uid = 0;
    protected static $user = null;
    protected static $key = null;
    public function __construct(App $app = null){
        parent::__construct($app);
        self::$key = Config::get('app.signature');
        $request = request();
        try {
            $authorization = $request->header('authorization');
            if($authorization){
//                $authorization = str_replace("Basic ", "", $authorization);
                $authorization = str_replace("Bearer ", "", $authorization);
                $jwt = $this->_checkAPIToken($authorization);
                if(time() > $jwt['exp']){
                    return $this->__json(403, 'token已失效请重新登录','',403);
                }
//                if(strpos($jwt['referer'],Config::get('app.referer')) !== false){
//                    return $this->__json(1,'登陆失效');
//                }
                self::$uid = $jwt['uid'];
                self::$user= $jwt;
            }else{
                return $this->__json(403,'请填写token',[],403);
            }
        } catch (\Exception $e) {
            return $this->__json(403,'请填写token',[],403);
        }

        /*$open_id = session('_open_id');
        if($open_id){
            $member = new Member();
            $user1 = $member::field('id')
                ->where('open_id', 'eq', $open_id)
                ->find();
            $user1 = $user1->toArray();
            self::$uid = $user1['id'] ? $user1['id'] : '';
        }else{
        //    exit(json_encode(['code'=>1,'msg'=>'授权失败']));
        }*/
    }

    /**
     * 生成密码
     * @param $password
     * @return bool|string
     */
    protected static function _password($password){
        return substr(md5($password),10,20);
    }

    /**
     * @param int $code
     * @param string $msg
     * @param array $data
     */
    public function __json($code=0,$msg='done',$data=[],$status=200){
        $data = $data?['code'=>$code,'msg'=>$msg,'data'=>$data]:
            ['code'=>$code,'msg'=>$msg];
        return response($data,$status,[],'json')
            ->send();
    }

    /**
     * 检测token
     * @param $ciphertext
     * @param array $alg
     * @return bool|mixed
     */
    private function _checkAPIToken(&$ciphertext,$alg = array('HS256')){
        $jwtObj = new Jwt();
        $key = self::$key; //key
        $decoded = $jwtObj::decode($ciphertext, $key, $alg);

        if(!empty($decoded) ){
            $jwtRet = json_decode(json_encode($decoded),true);
            return $jwtRet;
        }else{
            Log::error('Controller: Interfaces | _checkAPIToken | token out of time!');
            return false;
        }
    }
}